package com.zuikaku.nettychat.netty.framework;

import com.zuikaku.nettychat.netty.controller.ChatController;
import com.zuikaku.nettychat.netty.controller.TestController;
import com.zuikaku.nettychat.netty.controller.UserController;
import com.zuikaku.nettychat.netty.dto.NettyRequest;
import com.zuikaku.nettychat.netty.vo.ControllerType;
import com.zuikaku.nettychat.netty.vo.MethodType;
import io.netty.channel.socket.SocketChannel;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.HashMap;


@Component
public class ControllerManager implements InitializingBean {

    @Autowired
    private TestController testController;

    @Autowired
    private UserController userController;

    @Autowired
    private ChatController chatController;

    private HashMap<ControllerType,BaseController> controllerHashMap =new HashMap<>();

    /**
     * 执行请求
     * @param nettyRequest
     * @param socketChannel
     */
    public void handleRequest(NettyRequest nettyRequest, SocketChannel socketChannel){
        //根据NettyRequest的所属Controller，拿到对应Controller的实例
        ControllerType controllerType = ControllerType.values()[nettyRequest.controllerType];
        BaseController controllerInstance = controllerHashMap.get(controllerType);
        if(controllerInstance==null){
            System.err.println("没有找到ControllerType:"+controllerType+"的Controller实例");
            return;
        }
        //获取方法
        MethodType methodType =MethodType.getMethodTypeByNum(nettyRequest.methodType);
        try {
            Method method = controllerInstance.getClass().getMethod(methodType.getMethodName(),String.class,SocketChannel.class);
            if(method==null){
                System.err.println("Controller："+controllerType+"未找到："+methodType.getMethodName()+"方法");
                return;
            }
            String responseData = (String) method.invoke(controllerInstance,nettyRequest.data,socketChannel);
            if(!StringUtils.isEmpty(responseData)){
                //todo 调用NettyServer中，向客户端发回响应的方法
                NettyServer.sendResponseToClient(responseData,methodType,socketChannel);
            }
        }catch (Exception e){
                e.printStackTrace();
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        controllerHashMap.put(ControllerType.TEST,testController);
        controllerHashMap.put(ControllerType.USER,userController);
        controllerHashMap.put(ControllerType.CHAT,chatController);
    }
}
